/**
 * 剑指 Offer 32 - I. 从上到下打印二叉树
 * https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/
 */
const { displayBaseArray, createTreeNode } = require('../../libs/public');

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
function levelOrder(root) {
  if (!root) {
    return [];
  }
  let stack = [root];
  const result = [];
  while (stack.length) {
    const temp = [];
    for (let i = 0; i < stack.length; i += 1) {
      result.push(stack[i].val);
      if (stack[i].left) {
        temp.push(stack[i].left);
      }
      if (stack[i].right) {
        temp.push(stack[i].right);
      }
    }
    stack = temp;
  }
  return result;
}

console.log(displayBaseArray(levelOrder(createTreeNode([3, 9, 20, null, null, 15, 7]))));
